﻿using System;
using System.Collections.Generic;
using DyUi.Base.Interfaces;
using DyUi.Base.Interfaces.SubSystems;

namespace DyUi.Core.SubSystems
{
    public class MessageSubSystem : DyUiControllerSubSystem, IMessageSubSystem
    {
        List<Subscription> _subscriptions = new List<Subscription>();

        public virtual void PublishEvent(IDyUiComponent component, String eventName, Object arg)
        {
            foreach (var subscription in _subscriptions)
            {
                if (subscription.Predicate(eventName, arg))
                {
                    subscription.Callback(subscription.Id, eventName, arg);
                }
            }
        }

        public virtual Guid SubscribeToEvent(IDyUiComponent component, Func<String, Object, Boolean> predicate, Action<Guid, String, Object> callback)
        {
            var subscription = new Subscription { Id = Guid.NewGuid(), Component = component, Predicate = predicate, Callback = callback };

            _subscriptions.Add(subscription);

            return subscription.Id;
        }

        public class Subscription
        {
            public Guid Id;
            public IDyUiComponent Component;
            public Func<String, Object, Boolean> Predicate;
            public Action<Guid, String, Object> Callback;
        }
        
    }
}
